﻿using System;
using System.Collections.Generic;
using System.ComponentModel.Design;
using Engine;
using Engine.Graphics;
using Game;
using static Mekiasm.MekCraftingRecipe;

namespace Mekiasm
{
    public class CraftBookWidget : CanvasWidget
    {
        private RectangleWidget rectangleWidget = new RectangleWidget() { FillColor = Color.Gray };
        private ListPanelWidget listPanelWidget = new ListPanelWidget() { HorizontalAlignment = WidgetAlignment.Near, Direction = LayoutDirection.Vertical, SelectionColor = Color.LightGray };
        private BevelledRectangleWidget bevelled1 = new BevelledRectangleWidget() { BevelColor = Color.Magenta, CenterColor = Color.Gray, BevelSize = 2f };
        private TextBoxWidget textBoxWidget = new TextBoxWidget() { FontScale = 0.5f, Margin = new Vector2(10, 0), Size = new Vector2(200, 40) };
        private LabelWidget tipWidget = new LabelWidget() { Text = "搜索...", FontScale = 0.7f, Color = new Color(0, 0, 0, 96), Margin = new Vector2(10f, 0f),HorizontalAlignment=WidgetAlignment.Center };
        private CanvasWidget TextInput = new CanvasWidget() { Size= new Vector2(200, 40) };
        private CanvasWidget LeftContainer = new CanvasWidget() { Size = new Vector2(200, float.PositiveInfinity) };
        private CanvasWidget RightContainer = new CanvasWidget() { Size = new Vector2(440, float.PositiveInfinity) };
        private CanvasWidget CraftContainer = new CanvasWidget() { Size = new Vector2(float.PositiveInfinity)};
        private CanvasWidget DeviceContainer = new CanvasWidget() { Size = new Vector2(440, 40) };
        private ListPanelWidget devicesList = new ListPanelWidget() { HorizontalAlignment = WidgetAlignment.Near, Direction = LayoutDirection.Horizontal, SelectionColor = Color.LightGray };
        private StackPanelWidget LeftPanel = new StackPanelWidget() { Direction = LayoutDirection.Vertical, Margin = new Vector2(5) };
        private StackPanelWidget RightPanel = new StackPanelWidget() { Direction = LayoutDirection.Vertical };
        private StackPanelWidget panelRightHori = new StackPanelWidget() { Direction = LayoutDirection.Horizontal };
        private StackPanelWidget panelCraftVertival = new StackPanelWidget() { Direction = LayoutDirection.Vertical };
        private StackPanelWidget h1 = new StackPanelWidget() { Direction = LayoutDirection.Horizontal,VerticalAlignment=WidgetAlignment.Stretch };

        private BevelledButtonWidget CopyBtn = new BevelledButtonWidget()
        {
            Size = new Vector2(32f),
            Text = "+",
            VerticalAlignment = WidgetAlignment.Far,
            HorizontalAlignment=WidgetAlignment.Center
        };

        Dictionary<Interface.IDynamicCraft, List<MekRecipe>> devices = new Dictionary<Interface.IDynamicCraft, List<MekRecipe>>();

        LabelWidget labelWidget = new LabelWidget() { HorizontalAlignment = WidgetAlignment.Center, VerticalAlignment = WidgetAlignment.Near, Text = "Mek合成谱", FontScale = 0.7f, Color = Color.Black };

        int Position = 0;

        ComponentCraftDemoMachine demoMachine;

        Action Tick;

        ImageWidget leftBtn = new ImageWidget() { Texture = ContentManager.Get<Texture2D>("Mekiasm/Gui/Button/left"), Size = new Vector2(16, 32), VerticalAlignment = WidgetAlignment.Center };

        ImageWidget rightBtn = new ImageWidget() { Texture = ContentManager.Get<Texture2D>("Mekiasm/Gui/Button/right"), Size = new Vector2(16, 32), VerticalAlignment = WidgetAlignment.Center };

        List<MekRecipe> mekRecipes = null;

        Interface.IDynamicCraft craft = null;

        private ComponentMiner Miner;

        LabelWidget countLabel = new LabelWidget() { HorizontalAlignment = WidgetAlignment.Center, VerticalAlignment = WidgetAlignment.Center };

        public TerrainRaycastResult? TerrainRaycastResult;

        public CraftBookWidget(ComponentMiner miner,TerrainRaycastResult? raycastResult)
        {
            Miner = miner;
            TerrainRaycastResult = raycastResult;
            Size = new Vector2(660, 400);
            HorizontalAlignment = WidgetAlignment.Center;
            VerticalAlignment = WidgetAlignment.Center;
            CraftContainer.Margin = new Vector2(0,5);
            CopyBtn.Margin = new Vector2(5);
            TextInput.AddChildren(bevelled1); TextInput.AddChildren(textBoxWidget); TextInput.AddChildren(tipWidget);
            LeftPanel.AddChildren(TextInput); LeftPanel.AddChildren(listPanelWidget);
            DeviceContainer.AddChildren(devicesList);
            RightPanel.AddChildren(labelWidget); RightPanel.AddChildren(DeviceContainer); RightPanel.AddChildren(panelRightHori);
            panelRightHori.AddChildren(leftBtn); panelRightHori.AddChildren(panelCraftVertival); panelRightHori.AddChildren(rightBtn); panelRightHori.AddChildren(CopyBtn);
            panelCraftVertival.AddChildren(countLabel); panelCraftVertival.AddChildren(CraftContainer);
            textBoxWidget.TextChanged += (obj) =>
            {
                if (!string.IsNullOrEmpty(textBoxWidget.Text)) tipWidget.IsVisible = false;
                else tipWidget.IsVisible = true;
                ReloadListData();
            };
            listPanelWidget.Margin = new Vector2(0, 5);
            listPanelWidget.ItemWidgetFactory = (obj) =>
            {
                var canvasWidget = new CanvasWidget() { Size = new Vector2(200, 50), HorizontalAlignment = WidgetAlignment.Near };
                var stackPanel = new StackPanelWidget() { Direction = LayoutDirection.Horizontal, HorizontalAlignment = WidgetAlignment.Near };
                var v = (int)obj;
                var block = BlocksManager.Blocks[Terrain.ExtractContents(v)];
                var blockIconWidget = new MekBlockIconWidget() { Value = v, Size = new Vector2(48, 48) };
                var labelWidget1 = new LabelWidget() { Text = block.GetDisplayName(null, v), FontScale = 0.6f };
                stackPanel.Children.Add(blockIconWidget);
                stackPanel.Children.Add(labelWidget1);
                canvasWidget.Children.Add(stackPanel);
                return canvasWidget;
            };
            devicesList.ItemSize = 54f;
            devicesList.ItemWidgetFactory = (obj) => {
                var craft = obj as Interface.IDynamicCraft;
                var canvasWidget = new CanvasWidget() { Size = new Vector2(48, 64), HorizontalAlignment = WidgetAlignment.Center, VerticalAlignment = WidgetAlignment.Center };
                var bevelled = new BevelledRectangleWidget() { BevelSize = 2f, BevelColor = Color.Black };
                var block = BlocksManager.Blocks[Terrain.ExtractContents(craft.BlockValue)];
                var blockIconWidget = new MekBlockIconWidget() { Value = craft.BlockValue, Size = new Vector2(48, 64) };
                canvasWidget.AddChildren(bevelled);
                canvasWidget.AddChildren(blockIconWidget);
                return canvasWidget;
            };
            listPanelWidget.ItemClicked += (obj) =>
            {
                int v = (int)obj;
                //找合成普
                devices.Clear();
                foreach (var item in MekRecipes)
                {
                    foreach (var item2 in item.Value)
                    {
                        foreach (var item3 in item2.Results)
                        {
                            if (item3 == v)
                            {
                                if (!devices.TryGetValue(item.Key, out var list))
                                {
                                    list = new List<MekRecipe>();
                                    devices.Add(item.Key, list);
                                }
                                list.Add(item2);
                                break;
                            }
                        }
                        foreach (var item3 in item2.FuelResults)
                        {
                            if (item3 == v)
                            {
                                if (!devices.TryGetValue(item.Key, out var list))
                                {
                                    list = new List<MekRecipe>();
                                    devices.Add(item.Key, list);
                                }
                                list.Add(item2);
                                break;
                            }
                        }
                        foreach (var item3 in item2.Remains)
                        {
                            if (item3 == v)
                            {
                                if (!devices.TryGetValue(item.Key, out var list))
                                {
                                    list = new List<MekRecipe>();
                                    devices.Add(item.Key, list);
                                }
                                list.Add(item2);
                                break;
                            }
                        }

                    }
                }
                devicesList.ClearItems();
                foreach (var c in devices) devicesList.AddItem(c.Key);
                if (devicesList.Items.Count > 0)
                {
                    devicesList.ItemClicked(devicesList.Items[0]);
                }
                else
                {
                    ClearAllWidget(CraftContainer);
                }
            };
            devicesList.ItemClicked += (obj) => {
                ClearAllWidget(CraftContainer);
                craft = obj as Interface.IDynamicCraft;
                if (devices.TryGetValue(craft, out mekRecipes))
                {
                    Position = 0;
                    countLabel.Text = $"{Position + 1}/{mekRecipes.Count}";
                    var e = DatabaseManager.CreateEntity(GameManager.Project, "CraftDemo", true);
                    demoMachine = e.FindComponent<ComponentCraftDemoMachine>();
                    demoMachine.SetData(mekRecipes[Position], craft.SlotsCount, craft.CraftSlotIndies, craft.FuelCraftSlotIndies, craft.RemainSlotIndies, craft.ResultSlotIndies);
                    craft.GenerateRecipeWidget(CraftContainer, demoMachine, miner, ref Tick);
                }
                else
                {
                    countLabel.Text = $"";
                }

                if (TargetInventory != null && craft.BlockValue == ILibrary.GetBasicValue(TargetDeviceValue))
                {
                    CopyBtn.IsVisible = true;
                }
                else
                {
                    CopyBtn.IsVisible = false;
                }
            };
            LeftContainer.AddChildren(LeftPanel);
            RightContainer.AddChildren(RightPanel);
            h1.AddChildren(LeftContainer);
            h1.AddChildren(RightContainer);
            AddChildren(rectangleWidget);
            AddChildren(h1);
            leftBtn.Clicked = () => {
                if (mekRecipes != null)
                {
                    Position--;
                    if (Position < 0) Position = Math.Max(mekRecipes.Count - 1, 0);
                    countLabel.Text = $"{Position + 1}/{mekRecipes.Count}";
                    if (demoMachine != null && mekRecipes.Count > 0) demoMachine.SetData(mekRecipes[Position], craft.SlotsCount, craft.CraftSlotIndies,craft.FuelCraftSlotIndies, craft.RemainSlotIndies, craft.ResultSlotIndies);
                }
                else countLabel.Text = "";
            };
            rightBtn.Clicked = () => {
                if (mekRecipes != null)
                {
                    Position++;
                    if (Position == mekRecipes.Count) Position = 0;
                    countLabel.Text = $"{Position + 1}/{mekRecipes.Count}";
                    if (demoMachine != null && mekRecipes.Count > 0) demoMachine.SetData(mekRecipes[Position], craft.SlotsCount, craft.CraftSlotIndies,craft.FuelCraftSlotIndies, craft.RemainSlotIndies, craft.ResultSlotIndies);
                }
                else countLabel.Text = "";
            };
            //加载所有的方块列表
            InitList();
            ReloadListData();
            ClearAllWidget(CraftContainer);
        }

        private void ClearAllWidget(ContainerWidget containerWidget, int step = 0)
        {
            foreach (var c in containerWidget.Children)
            {
                if (c is ContainerWidget cc)
                {
                    ClearAllWidget(cc, step + 1);
                }
            }
            containerWidget.ClearChildren();
            if (step == 0)
            {
                Tick = null;
                CopyBtn.IsVisible = false;
                containerWidget.AddChildren(new RectangleWidget() { OutlineColor = new Color(255, 255, 255), OutlineThickness = 2f, FillColor = Color.Transparent });
            }
        }

        private List<int> vs = new List<int>();

        public void InitList()
        {
            foreach (var blocks in BlocksManager.Blocks)
            {
                foreach (var item2 in blocks.GetCreativeValues())
                {
                    vs.Add(item2);
                }
            }

        }

        public IInventory TargetInventory;

        public int TargetDeviceValue;

        public void SetCraftInventory(IInventory inventory, int value)
        {
            TargetDeviceValue = value;
            TargetInventory = inventory;
            var d = CopyBtn.Children.Find<RectangleWidget>();
            d.Subtexture = new Subtexture(ContentManager.Get<Texture2D>("Mekiasm/Gui/Overlay/overlay_plus"), Vector2.Zero, Vector2.One);
            d.Size = new Vector2(d.Subtexture.Texture.Width, d.Subtexture.Texture.Height);
            d.IsVisible = true;
            d.TextureLinearFilter = true;
            CopyBtn.Children.Find<LabelWidget>().IsVisible = false;
            if (devicesList.SelectedItem != null)
            {
                devicesList.ItemClicked(devicesList.SelectedItem);
            }
        }

        public void ReloadListData()
        {
            listPanelWidget.ClearItems();
            foreach (var item2 in vs)
            {
                var b = BlocksManager.Blocks[Terrain.ExtractContents(item2)].GetDisplayName(null, item2);
                if (string.IsNullOrEmpty(textBoxWidget.Text) || b.Contains(textBoxWidget.Text))
                {
                    listPanelWidget.AddItem(item2);
                }
            }
        }

        public override void Update()
        {
            if (CopyBtn.IsClicked)
            {
                if (TargetInventory is ComponentEnergyMachine machine)
                {
                    for (int i = 0; i < demoMachine.Slots.Count; i++)
                    {
                        var targetSlot = machine.Slots[i];
                        var sourceSlot = demoMachine.Slots[i];
                        targetSlot.Value = sourceSlot.Value;
                        targetSlot.Count = sourceSlot.Count;
                        targetSlot.FuelAmount = sourceSlot.FuelAmount;
                        targetSlot.FuelValue = sourceSlot.FuelValue;
                        targetSlot.FuelType = sourceSlot.FuelType;
                    }
                }
                Miner.ComponentPlayer.ComponentGui.ModalPanelWidget = null;
                Miner.Interact(TerrainRaycastResult.Value);
                
            }
            if (textBoxWidget.HasFocus)
            {
                var subp = ILibrary.Project.FindSubsystem<SubsystemPlayers>();
                foreach (var p in subp.ComponentPlayers)
                {
                    p.ComponentInput.AllowHandleInput = false;
                }
            }
            else
            {
                var subp = ILibrary.Project.FindSubsystem<SubsystemPlayers>();
                foreach (var p in subp.ComponentPlayers)
                {
                    p.ComponentInput.AllowHandleInput = true;
                }
            }
            demoMachine?.Update();
            Tick?.Invoke();
        }


    }
}
